package com.haohan.jingyuan.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * AES加密解密工具类
 *
 * @ClassName AesUtil
 * @Description AES加密解密工具
 * @Author hexijun
 * @Time 2025/01/19 12:00
 * @Version 1.0
 */
@Slf4j
public class AesUtil {

    /**
     * 加密算法
     */
    private static final String ALGORITHM = "AES";

    /**
     * 加密模式
     */
    private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";

    /**
     * AES加密
     *
     * @param plainText 明文
     * @param key       密钥
     * @return 加密后的Base64字符串
     */
    public static String encrypt(String plainText, String key) {
        if (!StringUtils.hasText(plainText)) {
            return plainText;
        }

        try {
            // 创建密钥
            SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), ALGORITHM);

            // 创建加密器
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);

            // 加密
            byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));

            // 返回Base64编码的字符串
            return Base64.getEncoder().encodeToString(encryptedBytes);
        } catch (Exception e) {
            log.error("AES加密失败", e);
            throw new RuntimeException("AES加密失败", e);
        }
    }

    /**
     * AES解密
     *
     * @param encryptedText 加密的Base64字符串
     * @param key           密钥
     * @return 解密后的明文
     */
    public static String decrypt(String encryptedText, String key) {
        if (!StringUtils.hasText(encryptedText)) {
            return encryptedText;
        }

        try {
            // 创建密钥
            SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), ALGORITHM);

            // 创建解密器
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            cipher.init(Cipher.DECRYPT_MODE, secretKey);

            // Base64解码
            byte[] encryptedBytes = Base64.getDecoder().decode(encryptedText);

            // 解密
            byte[] decryptedBytes = cipher.doFinal(encryptedBytes);

            return new String(decryptedBytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            log.error("AES解密失败", e);
            throw new RuntimeException("AES解密失败", e);
        }
    }
}
